from django.http import HttpResponse
from django.shortcuts import render
from dwebsocket import require_websocket
from dwebsocket.decorators import accept_websocket


def test(request):
    return render (request, 'dwebsocket.html')


@accept_websocket
def testSocket(request):
    if request.is_websocket ():
        print (1)
    request.websocket.send ('下载完成'.encode ('utf-8'))


# demo2
from dwebsocket import require_websocket


def index(request):
    return render (request, 'index.html')  # 会自动关闭


@require_websocket
def echo_once(request):
    message = request.websocket.wait ()
    request.websocket.send (message)


def index2(request):
    return render (request, 'index2.html')


@accept_websocket
def echo(request):
    if not request.is_websocket ():  # 判断是不是websocket连接
        try:  # 如果是普通的http方法
            message = request.GET['message']
            return HttpResponse (message)
        except:
            return render (request, 'index.html')
    else:
        for message in request.websocket:
            request.websocket.send (message)  # 发送消息到客户端
